# -*- coding: UTF-8 -*-
"""
@File ：product_category
@Author ：lucas
@Date ：2023-10-18 23:04:02
@Description: 
"""

import logging
from odoo import api, fields, models
from odoo.exceptions import UserError, ValidationError

_logger = logging.getLogger(__name__)


class JustdooProductCategory(models.Model):
    _name = 'justdoo.product.category'
    _description = '产品分类'
    _parent_name = "parent_id"
    _parent_store = True
    _rec_name = 'complete_name'
    _order = 'complete_name'

    name = fields.Char('名称', required=True, index=True)
    code = fields.Char(string='编码', index=True)
    parent_path = fields.Char(string='层级路径', index=True)
    parent_id = fields.Many2one('justdoo.product.category', '上级分类', index=True, ondelete='cascade')
    child_lines = fields.One2many('justdoo.product.category', 'parent_id', '子级分类')
    complete_name = fields.Char('全称', compute='_compute_complete_name', recursive=True, store=True)
    company_name = fields.Char('公司', default=lambda self: self.env.company.name)
    company_id = fields.Integer('公司ID', default=lambda self: self.env.company.id)

    _sql_constraints = [('uniq_name', 'unique (name)', '名称已存在请不要重复添加!')]

    @api.constrains('parent_id')
    def _check_parent(self):
        product_category_all = self.env.ref('justdoo_product.product_category_all')
        for record in self:
            if record.parent_id:
                continue
            if record.id == product_category_all.id:
                continue
            raise ValidationError('请设置好分类%s的上架分类信息' % record.name)

    @api.depends('name', 'parent_id.complete_name')
    def _compute_complete_name(self):
        for category in self:
            if not category.parent_id:
                category.complete_name = category.name
            else:
                category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)

    @api.constrains('parent_id')
    def _check_category_recursion(self):
        if not self._has_cycle():
            raise ValidationError('请仔细检查分类，可能存在递归引用')

    @api.ondelete(at_uninstall=False)
    def _unlink_except_default_category(self):
        main_category = self.env.ref('justdoo_product.product_category_all')
        if main_category in self:
            raise UserError('默认分类不可以删除')
